package com.seabook.store.purchase.web;

import java.util.List;


import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.seabook.store.auth.domain.User;
import com.seabook.store.auth.web.UserSession;
import com.seabook.store.purchase.domain.Cart;
import com.seabook.store.purchase.domain.Order;
import com.seabook.store.purchase.service.OrderService;
import com.seabook.store.util.PropertyManager;
import com.seabook.store.util.ServiceLocator;

@Controller
@SessionAttributes(types = Order.class)
public class OrderController {
    private final OrderService orderService;
    

    public OrderController() {
        this.orderService = (OrderService) ServiceLocator
                .getBean("orderService");
    }
    
    @RequestMapping(value = "/order/neworder")
    public String submitOrder(@ModelAttribute Order order, HttpServletRequest request){
        User user = UserSession.getUserSession(request).getUser();
        order.setUserId(user.getUserId());
        order = orderService.insertOrder(order);
        request.setAttribute("order", order);
        request.setAttribute("app.url", PropertyManager.getProperty("app.url"));
        request.setAttribute("paypal.url", PropertyManager.getProperty("paypal.url"));
        UserSession.getUserSession(request).setCart(new Cart());
        return "viewOrder";
    }
    
    @RequestMapping(value = "/order/vieworder")
    public String viewOrder(@RequestParam("orderId") int orderId , HttpServletRequest request){
        Order order = orderService.getOrderByOrderId(orderId);
        request.setAttribute("order", order);
        request.setAttribute("app.url", PropertyManager.getProperty("app.url"));
        return "viewOrder";
    }
    
    @RequestMapping(value = "/order/myorders")
    public String myOrders(HttpServletRequest request){
        User user = UserSession.getUserSession(request).getUser();
        List<Order> orders = orderService.getOrderByUserId(user.getUserId());
        request.setAttribute("orders", orders);
        return "myOrders";
    }
    
    @RequestMapping(value = "/order/{orderId}/confirmpayment")
    public String confirmPayment(@PathVariable int orderId,HttpServletRequest request){
        orderService.updateOrderStatus(orderId, Order.Status.PAID);
        Order order = orderService.getOrderByOrderId(orderId);
        request.setAttribute("order", order);
        request.setAttribute("msg", "We have received your payment and will deliver ASAP!");
        return "viewOrder";
    }
    
    
}
